import { useState } from "react";
import { Editor, Element, Transforms, Range, Node } from "slate";

type LinkEditor = {
  isLink: (element: any) => void;
  isLinkActive: () => boolean;
  unwrapLink: () => void;
  insertLink: (rl: string, text?: string) => void;
  getSelectedLinkText: () => string;

} & Editor;

export default (editor: LinkEditor) => {
  const { isInline: iseEditorInline } = editor;

  editor.isInline = (element: any) => {
    return element.type === "link" ? true : iseEditorInline(element);
  };

  editor.isLink = (element: any) => {
    return element.type === "link";
  };

  editor.isLinkActive = () => {
      if(!editor.selection){
          return false;
      }
      // Range.includes()
      // if(Range.isCollapsed(editor.selection)){
      //   return false
      // }

      const [link] = Editor.nodes(editor, {
        // at:editor.selection,
        match: n =>{
          return  !Editor.isEditor(n) && Element.isElement(n) && n.type === 'link'
        }
         
      })
      console.log(link)
      return !!link
  };

  editor.unwrapLink = () => {
    Transforms.unwrapNodes(editor, {
      match: (n) =>
        !Editor.isEditor(n) && Element.isElement(n) && n.type === "link",
    });
  };
  editor.updateLink = (url) => {
    Transforms.setNodes(editor, {url}, {
      match: n => !Editor.isEditor(n) && Element.isElement(n) && n.type === "link",
    })
  };
  editor.insertLink = (url: string, text?: string) => {
    if (!editor?.selection || !url) {
      return;
    }

        
    const { selection } = editor;
    const isCollapsed = selection && Range.isCollapsed(selection);
    const isActive=editor.isLinkActive()
    if (isActive) {
     
       editor.unwrapLink();
    }


    const link: any = {
      type: "link",
      url,
      children: isCollapsed ? [{ text: text }] : [],
    };

    if (!isActive&&isCollapsed) {
      Transforms.insertNodes(editor, link);
    } else {
      Transforms.wrapNodes(editor, link, { split: true });
      Transforms.collapse(editor, { edge: "end" });
    }
  };

  editor.getSelectedLinkText = () => {
    const selection = editor?.selection;
    if (selection) {
      return Editor.string(editor, selection);
    }
    return "";
  };
  return editor;
};
